package com.study.project.config.http;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class HttpComponent {

    @Autowired
    private RestTemplate restTemplate;

    public String getUrl(String url) {
        return restTemplate.getForObject(url, String.class);
    }

    public String postJson(String url, Object param, Map<String, List<String>> headerParam) {
        log.info("请求的地址为:{},参数为:{},请求头为:{}", url, JSON.toJSONString(param), headerParam);
        HttpHeaders header = new HttpHeaders();
        if (headerParam != null) {
            headerParam.forEach((k, v) -> {
                header.put(k, v);
            });
        }
        HttpEntity request = new HttpEntity<>(param, header);
        return restTemplate.postForObject(url, request, String.class);
    }

    public String post(String url, Object param) {
        log.info("请求的地址为:{},参数为:{}", url, JSON.toJSONString(param));
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);

        log.info("请求头:{}", JSONObject.toJSONString(headers));
        HttpEntity request = new HttpEntity<>(param, headers);
        return restTemplate.postForObject(url, request, String.class);
    }

    public String post2(String url, Object param, Map<String, List<String>> headerParam) {
        HttpHeaders header = new HttpHeaders();
        if (headerParam != null) {
            headerParam.forEach((k, v) -> {
                header.put(k, v);
            });
        }
        HttpEntity request = new HttpEntity<>(param, header);
        return restTemplate.postForObject(url, request, String.class);
    }
}
